<template>
  <div>
    <el-form ref="form" :rules="rules" :model="form"
             label-width="0px">

      <el-form-item label="" prop="emailInput">
        <el-input v-model.trim.trim="form.emailInput" placeholder="请输入手机号或邮箱"
                  maxlength="50" show-word-limit class="limit">
          <span slot="prefix" class="svg-container">
            <!-- <svg-icon icon-class="user_login" class="el-input__icon input-icon" /> -->
            <img src="../../../assets/user-icon.png" draggable="false">
          </span>
        </el-input>
      </el-form-item>
      <el-form-item label="" prop="verificationCode">
        <el-input v-model.trim="form.verificationCode" placeholder="请输入验证码"
                  maxlength="6" style="width: 65%;">
          <span slot="prefix" class="svg-container">
            <!-- <svg-icon icon-class="user_login" class="el-input__icon input-icon" /> -->
            <img src="../../../assets/code-icon.png" draggable="false">
          </span>
        </el-input>
        <el-button v-if="!emailflag || totaltime <= 0" class="getcode"
                   @click="sendCode">获取验证码</el-button>
        <el-button v-if="emailflag && totaltime > 0" class="getcode">{{ totaltime }}秒</el-button>
      </el-form-item>
      <el-form-item prop="newPwd">
        <el-input
          v-model.trim="form.newPwd"
          type="password"
          :placeholder="`请输入密码`"
        >
          <span slot="prefix" class="svg-container">
            <!-- <svg-icon icon-class="user_login" class="el-input__icon input-icon" /> -->
            <img src="../../../assets/password-icon.png" draggable="false">
          </span>
        </el-input>
      </el-form-item>
      <el-form-item prop="surepassword" style="margin-bottom: 40px;">
        <el-input
          v-model.trim="form.surepassword"
          type="password"
          placeholder="请输入重复密码"
        >
          <span slot="prefix" class="svg-container">
            <!-- <svg-icon icon-class="user_login" class="el-input__icon input-icon" /> -->
            <img src="../../../assets/password-icon.png" draggable="false">
          </span>
        </el-input>
      </el-form-item>
      <div class="btn-wrap">
        <el-button
          class="nextbtn"
          @click="$emit('backLogin')"
        >返回登录</el-button>
        <el-button
          class="nextbtn"
          type="primary"
          @click="submit"
        >确定</el-button>
      </div>
      <!-- <p class="tips">
        提示：如果您的电话/邮箱不可使用，请您通过其他方式联系系统管理员
      </p> -->
    </el-form>
  </div>
</template>

<script>
import { getTenantDropDownList } from '@/framework/api/user'
import { checkEmail, checkPhone } from '@/framework/utils/validate'
import { encryption, decryption } from 'DQBasic-vue-component'
import { sendMailCode, validatorAuthCode, setNewPassword, getPwdRole } from '@/framework/api/userCenter/sysUser'

export default {
  data() {
    const validateEmailInput = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入手机号或邮箱'))
      } else if (!checkEmail(value) && !checkPhone(value)) {
        callback(new Error('手机号或邮箱格式不正确'))
      } else {
        callback()
      }
    }
    const validatePassword = (rule, value, callback) => {
      if (!value) {
        callback('请输入密码')
      } else if (this.pwdreg.test(value) === false) {
        callback(this.pwdregcon)
      } else {
        callback()
      }
    }
    const validatePass = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请再次输入密码'))
      } else if (value !== this.form.newPwd) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }
    const validatePhone = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入手机号/电话'))
      } else if (!checkPhone(value)) {
        callback(new Error('请输入合法的手机号/电话'))
      } else {
        callback()
      }
    }
    return {
      loading: false,
      active: 1,
      form: {
        tenantId: '000000',
        email: '',
        newPwd: '',
        surepassword: '',
        verKeyEmail: '',
        verificationCode: ''
      },
      rules: {
        tenantId: [{ required: true, trigger: 'change', message: '请选择租户' }],
        emailInput: [
          { required: true, trigger: 'change', validator: validateEmailInput }
        ],
        phone: [
          { required: true, trigger: 'change', validator: validatePhone }
        ],
        verificationCode: [
          { required: true, trigger: 'blur', message: '请输入验证码' }
        ],
        newPwd: [
          { required: true, trigger: 'blur', validator: validatePassword }
        ],
        surepassword: [
          { required: true, trigger: 'blur', validator: validatePass }
        ]
      },
      emailflag: false,
      okflag: false,
      selectList: [],
      timenum: 3,
      timer: '',
      zfscontent: '120s后再次发送',
      totaltime: 120,
      timer2: null,
      verImage: '',
      disabled: false,
      emailRequestId: '',
      text: '测试',
      kaptchaRequestId: '',
      pageKaptchaWidth: '',
      pwdreg: '',
      pwdregcon: '',
      pwdrole: ''
    }
  },
  mounted() {
    this.getPwdRole()
  },
  methods: {
    submit() {
      this.validatorAuthCode(2)
    },
    // 发送验证码
    sendCode() {
      if (!this.form.tenantId) {
        this.$message({
          message: '请选择租户',
          type: 'error'
        })
      } else if (!this.form.emailInput) {
        this.$message({
          message: '请输入手机号或邮箱',
          type: 'error'
        })
      } else {
        if (checkPhone(this.form.emailInput)) {
          this.form.phone = this.form.emailInput
          this.form.email = ''
        }
        if (checkEmail(this.form.emailInput)) {
          this.form.phone = ''
          this.form.email = this.form.emailInput
        }
        const form = encryption({
          data: this.form
        })
        sendMailCode(form).then((response) => {
          this.$message({
            message: '发送成功',
            type: 'success'
          })
          this.time120()
          const res = decryption(response)
          this.form.smsRequestId = res.data.smsRequestId
          this.form.emailOrPhone = res.data.emailInput
        })
      }
    },
    // 校验验证码
    validatorAuthCode(n) {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          const form = encryption({
            data: this.form
          })
          validatorAuthCode(form).then((response) => {
            this.$message({
              message: '验证成功',
              type: 'success'
            })
            this.active = n
            // this.getPwdRole()
            this.onSubmit(3, true)
          })
        }
      })
    },
    // 获取密码策略
    getPwdRole() {
      getPwdRole({ tenantId: this.form.tenantId }).then((res) => {
        this.pwdrole = res.data
        this.pwdreg = new RegExp(this.pwdrole.pwdRegularExpression)
        this.pwdregcon = this.pwdrole.pwdRgDescribe
      })
    },
    time120() {
      this.emailflag = true
      this.totaltime = 120
      this.zfscontent = `${this.totaltime}s后再次发送`
      if (!this.timer2) {
        this.timer2 = setInterval(() => {
          if (this.totaltime > 0 && this.totaltime <= 120) {
            this.totaltime--
            this.zfscontent = `${this.totaltime}s后再次发送`
          } else {
            clearInterval(this.timer2)
            this.emailflag = false
            this.timer2 = null
            // this.zfscontent = '再次发送'
          }
        }, 1000)
      }
    },
    // 修改密码
    onSubmit(n, flag) {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          // 完成跳转登录
          if (n === 3 && flag) {
            this.okflag = false
            const obj3 = {
              email: this.form.email,
              phone: this.form.phone,
              newPwd: this.form.newPwd,
              tenantId: this.form.tenantId
            }
            const password = encryption({
              data: obj3
            })

            setNewPassword(password).then((res) => {
              if (res.success) {
                this.$message({
                  message: '修改成功',
                  type: 'success'
                })
                this.active = n
                this.okflag = true
                if (!this.timer) {
                  this.timenum = 3
                  this.timer = setInterval(() => {
                    if (this.timenum > 0 && this.timenum <= 3) {
                      this.timenum--
                    } else {
                      clearInterval(this.timer)
                      this.timer = null
                      // 先退出清空
                      // this.$store.dispatch('user/logout')
                      this.$router.push({
                        path: '/login'
                      })
                    }
                  }, 1000)
                }
              } else {
                this.$message({
                  message: res.message,
                  type: 'error'
                })
              }
            })
          }
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
::v-deep .el-form-item {
  margin-bottom: 16px;
}
::v-deep .el-form-item__error {
  padding-top: 2px;
}
::v-deep .el-input {
    display: inline-block;
    height: 40px !important;
    width: 100%;
    background: #FFFFFF;
    border-radius: 4px 4px 4px 4px;
    opacity: 1;
    input {
      height: 40px !important;
      // border: 1px solid #DCDFE6;
      border: 1px solid #D9D9D9;
    }
     .el-input__icon{
      font-size: 16px;
    }
  }
  .getcode{
    position: absolute;
    right: 0;
    top: 50%;
    transform: translateY(-50%);
    font-size: 14px;
    font-family: MicrosoftYaHei;
    border-radius: 4px;
    width: 33%;
    height: 40px;
    border: 1px solid #1289FF;
    color: #1289FF;
    // border-left: 1px solid #091934;
  }
  .btn-wrap {
    display: flex;
    justify-content: space-between;
    .nextbtn {
      width: 160px;;
      height: 40px;
    }
  }
  .svg-container {
    // padding: 6px 5px 6px 15px;
    line-height: 45px;
    // color: $dark_gray;
    vertical-align: middle;
    width: 16px;
    display: inline-block;
    img {
      width: 100%;
    }
  }
</style>
